package com.achievo.know.pojo;


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
  
@SuppressWarnings("restriction")
public class ImageZipUtil {   
	static Logger _log = Logger.getLogger(ImageZipUtil.class);
    /**  
     * 压缩图片文件<br>  
     * 先保存原文件，再压缩、上传  
     *   
     * @param oldFile  
     *            要进行压缩的文件全路径  
     * @param width  
     *            宽度  
     * @param height  
     *            高度  
     * @param quality  
     *            质量  
     * @param smallIcon  
     *            小图片的后缀  
     * @return 返回压缩后的文件的全路径  
     */  
    public static String zipImageFile(String path,String oldFile, int width, int height,   
            float quality, String smallIcon) {   
        if (oldFile == null) {   
            return null;   
        }   
        String newImage = null;   
        try {   
            /** 对服务器上的临时文件进行处理 */  
        	File f=new File(oldFile);
        	BufferedImage srcFile = ImageIO.read(f);   
            /** 宽,高设定 */  
            double sx = (double) width / srcFile.getWidth();    
            double sy = (double) height / srcFile.getHeight();    
            // 这里想实现在targetW，targetH范围内实现等比缩放。如果不需要等比缩放    
            // 则将下面的if else语句注释即可    
            if (sx < sy) {    
                sx = sy;    
                width = (int) (sx * srcFile.getWidth());    
            } else {    
                sy = sx;    
                height = (int) (sy * srcFile.getHeight());    
            }
            BufferedImage tag = new BufferedImage(width, height,   
                    BufferedImage.TYPE_INT_RGB);   
            tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);  
            String filePrex = f.getName().substring(0, f.getName().indexOf('.'));
            //String filePath= oldFile.substring(0, oldFile.indexOf('.'));
            /** 压缩后的文件名 */  
            newImage = filePrex + smallIcon   
                    + f.getName().substring(filePrex.length());  
            /** 压缩之后临时存放位置 */  
            FileOutputStream out = new FileOutputStream(path+newImage);   
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);   
            /** 压缩质量 */  
            jep.setQuality(quality, true);   
            encoder.encode(tag, jep);   
            out.close();   
  
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        return newImage;   
    }   
    
  
    /**
     * Save file as a new,area and new size given. If any of the coordinate is negative,
     * all the original image will be copied to.
     * @param toFolderPath Folder for new image to store.
     * @param orgImage Original source image.
     * @param x X area start of original image area to get.
     * @param y Y area start of original image area to get.
     * @param width Width of original image area to get.
     * @param height  Height of original image area to get.
     * @param toWidth New image width. If not positive, width will same as the area.
     * @param toHeight New image height. If not positive, width will same as the area.
     * @param quality
     * @param nameTag  Name tag may needed.
     * @param toName File name of new but will add with tag in the end before file extension.
     * @param keepAspectRatio
     * if empty, use the original file name with tag added.
     * @return the final name of the new image.
     * @throws Exception 
     */
    public static String zipAreaImageFile(String toFolderPath,File orgImage, 
    		int x, int y,int width, int height,
    		int toWidth, int toHeight, float quality, 
    		String nameTag, String toName, boolean keepAspectRatio) throws Exception {
    	if(x < 0 || y < 0){
    		throw new Exception("x or y must not be negative.");
    	}
        if (orgImage == null || !orgImage.exists()) {   
            return null;   
        }   
        String newImageName = null;   
        try {
        	//获取源文件
        	BufferedImage srcFile = ImageIO.read(orgImage);   
        	
        	//截取源图片的区域，如果全为非正数，表示整张图片。
        	if(width <= 0 || height <=0 ){
        		width = srcFile.getWidth();
        		height = srcFile.getHeight();
        	}else{
        		//解决截取范围可能超过图片本身大小的问题
        		if((x + width) > srcFile.getWidth()){
        			width = srcFile.getWidth() - x;
        		}
        		if((y + height) > srcFile.getHeight()){
        			height = srcFile.getHeight() - y;
        		}
        		srcFile = srcFile.getSubimage(x, y, width, height);
        	}
        	
        	//指定长宽的新图片,如果不是正数，则表示与截取区域的长，宽相同。
        	if(toWidth <= 0 ||  toHeight <=0){
    			toWidth = width;
    			toHeight = height;
    		}
        	
        	/* 保持同比例缩放 */
			if (keepAspectRatio) {
				double sx = (double) toWidth / srcFile.getWidth();
				double sy = (double) toHeight / srcFile.getHeight();
				// 这里想实现在targetW，targetH范围内实现等比缩放。如果不需要等比缩放
				// 则将下面的if else语句注释即可
				if (sx < sy) {
					sx = sy;
					toWidth = (int) (sx * srcFile.getWidth());
				} else {
					sy = sx;
					toHeight = (int) (sy * srcFile.getHeight());
				}

			}
        	
            BufferedImage newImg = new BufferedImage(toWidth, toHeight,
                    BufferedImage.TYPE_INT_RGB); 
            //把源图片的指定区域画到新图片；如果没有指定区域，则全部
            newImg.getGraphics().drawImage(srcFile, 0, 0, toWidth,toHeight, null);
            
            /** 压缩后的文件名 */
            if(toName != null && !"".equals(toName)){
            	/* Name prefix part. */
            	newImageName = toName.substring(0, toName.lastIndexOf('.'));
            	String filePrex = toName.substring(newImageName.length());
            	if(nameTag != null){
            		newImageName = newImageName + nameTag + filePrex;
            	}
            }else{
            	newImageName = orgImage.getName();
            	if(nameTag != null){
            		/* Name prefix part. */
            		newImageName = orgImage.getName().substring(0,orgImage.getName().lastIndexOf('.'));
            		String filePrex = orgImage.getName().substring(newImageName.length());
            		newImageName = newImageName + nameTag + filePrex;
            	}
            } 
            _log.debug("newImageName:" + newImageName);
            
            /** 压缩之后临时存放位置 */  
            FileOutputStream out = new FileOutputStream(toFolderPath + newImageName);   
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(newImg);   
            /** 压缩质量 */  
            jep.setQuality(quality, true);   
            encoder.encode(newImg, jep);   
            out.close();   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        return newImageName;   
    }   
    
    /**  
     * 保存文件到服务器临时路径  
     *   
     * @param fileName  
     * @param is  
     * @return 文件全路径  
     */  
    public static String writeFile(String fileName, InputStream is) {   
        if (fileName == null || fileName.trim().length() == 0) {   
            return null;   
        }   
        try {   
            /** 首先保存到临时文件 */  
            FileOutputStream fos = new FileOutputStream(fileName);   
            byte[] readBytes = new byte[512];// 缓冲大小   
            int readed = 0;   
            while ((readed = is.read(readBytes)) > 0) {   
                fos.write(readBytes, 0, readed);   
            }   
            fos.close();   
            is.close();   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        return fileName;   
    }   
    public static void main(String args[]){   
       ImageZipUtil.zipImageFile("C:\\", "F:\\ProgramData\\Files\\news\\201108\\a1b40edc478144c18901260deb743f5a.jpg",400, 400, 0.75f, "icon");   
           
    }   
}  
